package com.wwj.cases;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.wwj.Constant.Constant;
import com.wwj.pojo.API;
import com.wwj.pojo.Case;
import com.wwj.pojo.JsonPathValidate;
import com.wwj.utils.DataUtils;
import com.wwj.utils.ExcelUtils;
import com.wwj.utils.HttpUtils;
import com.wwj.utils.SQLUtils;
import org.apache.commons.lang3.StringUtils;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.List;

/**
 * 充值测试用例
 */
public class RechargeCase extends BaseCase{

    @Test(dataProvider = "datas",description = "充值")
    public void testRecharge(API api, Case c){

        //获取全局变量，进行替换，未知不知道有几个需要替换的变量
        String params = paramReplace(c.getParams());
        System.out.println("params:"+params);
        String sql = paramReplace(c.getSql());
        System.out.println("sql:"+sql);
        //参数需要设置回去
        c.setParams(params);
        c.setSql(sql);
        //1.数据库前置查询结果

        //1.数据库前置查询结果
        Object beforeSQLResult = SQLUtils.query(sql);

        //2.调用接口
        String content = call(api, c);
        //3.添加回写内容
        addWriteBackData(c.getCaseId(),Constant.ACTUAL_RESPONSE_DATA_CELLNUM,content);
        //4.开始断言
        boolean assertResponseData = assertResponseData(c, content);
        //5.数据库后置查询
        Object afterSQLResult = SQLUtils.query(sql);
        boolean assertSQL = true;
        if(StringUtils.isNoneBlank(sql)){
            assertSQL = assertSQL(beforeSQLResult, afterSQLResult,c);
            System.out.println("数据库断言结果是:"+assertSQL);
        }
        //判断最终结果，响应断言和数据库断言一起进行判断
        String passContent = (assertResponseData && assertSQL)?"Pass":"Fail";

        addWriteBackData(c.getCaseId(),Constant.ASSERT_CELLNUM,passContent);
}

    /**进行充值部分的断言
     * @param beforeSQLResult
     * @param afterSQLResult
     * @param c
     * @return
     */
    private boolean assertSQL(Object beforeSQLResult,Object afterSQLResult,Case c) {
        double money = Double.parseDouble(JSONPath.read(c.getParams(), "$.amount").toString());
        double beforeMoney = Double.parseDouble(beforeSQLResult.toString());
        double afterMoney = Double.parseDouble(afterSQLResult.toString());
        return afterMoney-beforeMoney==money;

    }



    @AfterSuite
    public void finish(){
        System.out.println("===执行批量回写====");
        //套件执行完，再执行批量回写
        ExcelUtils.write(Constant.EXCEL_PATH,1);
    }


    @DataProvider(name = "datas")
    public Object[][] datas(){
        Object[][] datas= DataUtils.getAPIAndByAPIId("3");
        //{{API,Case},{},.....}
        return datas;

    }
}
